package com.genersoft.iot.vmp.tencent;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class TencentCloud {

    protected  static COSClient cosClient;

    protected final static String secretId ="AKIDWoBIAlHRZR2MN7kyOYicGp8C3qNs2j6D";
    protected final static String secretKey ="zjY6h5E7j4BLCoX2GG1Xo8aCYx6yav0q";

    protected final static String bucketName = "wgc-1302584481";
    protected final static String apCity = "ap-guangzhou";

    public TencentCloud(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region regin = new Region(apCity);
        ClientConfig clientConfig = new ClientConfig(regin);
        cosClient = new COSClient(cred,clientConfig);
    }


    /**
     *
     * @describe 上传文件的方法
     * @methods uploadObject 方法名
     * @parameter  fileUrl 上传文件地址
     * @parameter  fileKey 文件对象名称
     * @parameter @return 对象列表
     */
    public static String uploadObject(String fileUrl, String fileKey) {
        try {
            if (cosClient ==null){
                new TencentCloud();
            }
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            // 指定要上传的文件
            File localFile = new File(fileUrl);
            String url = "/Public/Uploads/zhengshu/"+dateFormat.format(new Date())+"/"+fileKey;
            // fileKey 指定要上传到 COS 上对象键
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, url, localFile);
            cosClient.putObject(putObjectRequest);
            return url;
        } catch (CosServiceException serverException) {
            throw  new RuntimeException("上传文件平台Server异常"+serverException.getErrorMessage());
        } catch (CosClientException clientException) {
            throw  new RuntimeException("上传文件平台Client异常"+clientException.getMessage());
        }

    }

    public static void main(String[] args) {
        System.out.println(uploadObject("D:\\Project\\image\\2023-12\\0.mp4","0.mp4"));
    }
}
